import { gameController } from "./gameController";
import Shape, { ShapeType } from "./Shape";
import ShapeItem from "./ShapeItem";
import BaseComp from "./ui/baseComp";
import { createRandom } from "./utils/util";

const {ccclass, property} = cc._decorator;
/**
 * 
 * 形状管理器
 * 
 */
@ccclass
export default class ShapeManager {
    public shapeArr: cc.Prefab[] = [];
    public map: cc.Node[][] = [];


    private shapeNameArr: ShapeType[] = [ShapeType.I,ShapeType.J,ShapeType.L,ShapeType.O,ShapeType.S,ShapeType.T,ShapeType.Z];

    private frames: cc.SpriteAtlas = null;

    /** 存放已经稳定的形状数组 */
    private shapesRoot: cc.Node = null;
    /** 形状出生时的父节点 */
    private bornRoot: cc.Node = null;
    public mapRoot: cc.Node = null;

    public init(shapesParent: cc.Node,bornRoot: cc.Node,shapeArr: cc.Prefab[],mapRoot: cc.Node,frames: cc.SpriteAtlas): void {
        this.shapesRoot = shapesParent;
        this.bornRoot = bornRoot;
        this.shapeArr = shapeArr;
        this.mapRoot = mapRoot;
        this.frames = frames;
    }

    public createShape(): Shape {
        if(this.shapeArr.length === 0) return;
        const randomShapeIndex = createRandom(0,7);

        // const randomShapeIndex = 0;
        const shapeNode = cc.instantiate(this.shapeArr[randomShapeIndex]);
        const shapeComp = shapeNode.getComponent(Shape);
        shapeComp.shapeType = this.shapeNameArr[randomShapeIndex];
        shapeNode.parent = this.bornRoot;
        if(shapeComp.shapeType === ShapeType.I) {
            shapeNode.setPosition(cc.v2(0,32));
        }
        if(shapeComp.shapeType === ShapeType.O) {
            shapeNode.setPosition(cc.v2(16,0));
        }
        const frameLen = this.frames.getSpriteFrames().length;
        const frameIndex = createRandom(0,frameLen);
        const targetFrame = this.frames.getSpriteFrames()[frameIndex];

        shapeNode.children.forEach(itemNode => {
            const sprite = itemNode.getComponent(cc.Sprite);
            itemNode.addComponent(ShapeItem);
            sprite.spriteFrame = targetFrame;
            // itemNode.color = new cc.Color().fromHEX(randomColor)
            const itemNodeWorldPos = itemNode.parent.convertToWorldSpaceAR(itemNode.getPosition());
            const itemMapLocalPos = this.mapRoot.convertToNodeSpaceAR(itemNodeWorldPos);

            const rowColObj = gameController.getRowByPoint(itemMapLocalPos);
            shapeComp.setSonsInMap(itemNode.uuid,rowColObj);
        })
        return shapeNode.getComponent(Shape);
    }

    public prepareNextShape(): Shape {
        
        gameController.game.recoverNormalSchedule();
        const shape = this.createShape();
        return shape;
    }

    public checkClear() {
        const clearUpRows = gameController.game.checkCanCleanUp();
        if(clearUpRows.length > 0) {
            gameController.game.clearUp(clearUpRows);
        }
    }
}
